package com.qzsf.backend.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.qzsf.backend.common.Result;
import com.qzsf.backend.dto.FeedbackCreateDTO;
import com.qzsf.backend.dto.FeedbackStats;
import com.qzsf.backend.entity.Feedback;
import com.qzsf.backend.mapper.FeedbackMapper;
import com.qzsf.backend.service.FeedbackService;
import com.qzsf.backend.util.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

/*
 * @Author: Dennis Chen
 * @CreateTime: 2024/11/24 22:17 周日
 * @Email 1429278462@qq.com
 * @Remark 反馈服务层实现类
 * @Version 1.0
 */
@Service
public class FeedbackServiceImpl implements FeedbackService {
    @Autowired
    private FeedbackMapper feedbackMapper;
    @Override
    public Result getFeedbackByCondition(Integer typeId, Integer eventId, int pageNo, int pageSize) {
        PageHelper.startPage(pageNo, pageSize);
        return Result.success(new PageInfo<>(feedbackMapper.getFeedbackByCondition(typeId, eventId)));
    }

    @Override
    public Result getFeedbackStats(Integer eventId, Integer typeId) {
        FeedbackStats stats = new FeedbackStats();

        // 获取反馈总数
        int totalFeedbacks = feedbackMapper.countFeedbacks(eventId, typeId);
        stats.setTotalFeedbacks(totalFeedbacks);

        // 获取评分分布
        List<Map<String, Object>> ratingDistribution = feedbackMapper.getRatingDistribution(eventId, typeId);
        stats.setRatingDistribution(ratingDistribution);

        // 获取平均评分
        Double averageRating = feedbackMapper.getAverageRating(eventId, typeId);
        stats.setAverageRating(averageRating);

        // 获取参与人数
        int totalParticipants = feedbackMapper.countUniqueParticipants(eventId, typeId);
        stats.setTotalParticipants(totalParticipants);

        return Result.success(stats);
    }

    @Override
    public Result createUserFeedback(FeedbackCreateDTO feedbackCreateDTO) {
        Map<String,Object> map = ThreadLocalUtil.get();
        int id = (int) map.get("id");
        Feedback feedback = new Feedback(id,feedbackCreateDTO);
        if(feedbackMapper.createFeedback(feedback)>0){
            return Result.success();
        }else{
            return Result.error("评价失败");
        }
    }
}
